package com.tian.view.anim.view_group_child

import android.os.Bundle
import android.view.Gravity
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.LinearLayout
import androidx.fragment.app.Fragment
import com.google.android.material.button.MaterialButton
import com.tian.view.databinding.FragmentAnimateLayoutChangesBinding

/**
 * @author tiansongtao, Email:tiansongtao@up366.com
 * @date 2022/12/29 14:12
 *
 * 通过xml 设置 ViewGroup android:animateLayoutChanges="true"
 * 可以实现 ViewGroup中添加、删除子控件时的动画，该动画为默认动画，
 *
 * 其实这个参数构建的是 ViewGroup的 LayoutTransition, android:animateLayoutChanges="true"
 * 会给 ViewGroup设置一个默认的 LayoutTransition,
 *
 * ViewGroup中代码
 *      case R.styleable.ViewGroup_animateLayoutChanges:
 *          boolean animateLayoutChanges = a.getBoolean(attr, false);
 *              if (animateLayoutChanges) {
 *                  setLayoutTransition(new LayoutTransition());
 *              }
 *          break;
 *
 *  默认的LayoutTransition 其实平时都够用了，我们也可以自定义动画构建LayoutTransition，
 *  使用 ViewGroup的 [ViewGroup.setLayoutTransition] 来设置
 *
 */
class AnimateLayoutChangesFragment : Fragment() {

    private lateinit var b: FragmentAnimateLayoutChangesBinding
    private var index = 0

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        b = FragmentAnimateLayoutChangesBinding.inflate(inflater)
        return b.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        initView()
    }

    private fun initView() {
        /**
         * b.llAnim 设置了 android:animateLayoutChanges="true"
         * 所以他又 layoutTransition, 这里我们可以从新给他设置动画时间
         */
        b.llAnim.layoutTransition.setDuration(2000)
        b.mbtAdd.setOnClickListener {
            val view = createButton(false)
            b.llNoAnim.addView(view, 0)
            val v = createButton(true)
            b.llAnim.addView(v, 0)
            index++
        }
        b.mbtRemove.setOnClickListener {
            if (b.llNoAnim.childCount > 0) {
                b.llNoAnim.removeViewAt(0)
            }
            if (b.llAnim.childCount > 0) {
                b.llAnim.removeViewAt(0)
            }
        }
    }

    private fun createButton(anim: Boolean): View {
        val bt = MaterialButton(requireContext())
        val lp = LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT)
        bt.layoutParams = lp
        bt.text = if (anim) "有动画-${index + 1}" else "无动画-${index + 1}"
        bt.gravity = Gravity.CENTER
        return bt
    }
}